/*
 * *
 *  * Created with IntelliJ RustRover.
 *  * Description:
 *  * Copyright Author: ZhenYi
 *  * DateTime: 2024/2/15 下午6:53
 *
 */


use salvo::prelude::*;
use sea_orm::{DatabaseConnection, EntityTrait};
use serde::*;
use crate::config::pgsql::userlist;

#[derive(Serialize, Deserialize)]
pub struct UserListInput {
    pub page: String,
    pub genre: String,
    pub nums: String
}
#[handler]
pub async fn get_user_list(req: &mut Request, depot: &mut Depot, res: &mut Response)  {
    let input = match req.parse_json::<UserListInput>().await{
        Ok(input) => input,
        Err(_) => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Json parse error\"}");
            return;
        }
    };
    let db = depot.obtain::<DatabaseConnection>().unwrap();
    let page = match input.page.parse::<i32>(){
        Ok(o) => o,
        Err(_) => {
           res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Page should be a number\"}");
                return;
        }
    };
    let nums = match input.nums.parse::<i32>() {
        Ok(o) => o,
        Err(_) => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Nums should be a number\"}");
            return;
        }
    };
    let genre = match input.genre.parse::<i32>(){
        Ok(o)=>o,
        Err(_) => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Genre should be a number\"}");
            return;
        }
    };
    if genre == -1 {
        let ds = userlist::Entity::find()
            .all(db)
            .await
            .unwrap();
        let mut ns = Vec::new();
        for (i,n) in ds.iter().enumerate(){
            if i > ((page + 1) * nums).try_into().unwrap()  {
                break;
            }else if i < (page * nums).try_into().unwrap() {
                continue
            }
            ns.push(n.clone());
        }
        let json = serde_json::to_string(&ds).unwrap();
        res.status_code(StatusCode::ACCEPTED).render(format!("{}",json));
        return;
    }else {
        let ds = userlist::Entity::find()
            .all(db)
            .await
            .unwrap();
        let mut ns = Vec::new();
        let mut np = 0;
        for (_i,n) in ds.iter().enumerate(){
            if np > (page + 1) * nums  {
                break;
            }else if np < page * nums {
                continue
            }
            if n.genre == genre {
                np += 1;
                ns.push(n.clone());
            }
        }
        let json = serde_json::to_string(&ns).unwrap();
        res.status_code(StatusCode::ACCEPTED).render(format!("{}",json));
        return;
    }
}